/*
 * @Description:
 * @Author: mmzhang
 * @Date: 2021-12-10 15:47:09
 * @LastEditTime: 2023-02-20 10:48:39
 */
import userApi from '@/config/server/api/user'
import customerApi from '@/config/server/api/customer'
import tool from '@/common/tool.js'
import dt from '@dt/dt'
import ruleOpt from '@/biz/option/rule.js'

function getName(userName) {
  let data = {
    userName
  }
  if (tool.getStorage('isbuildFlag') == 'buildpage') {
    data.buildingId = dt.buildInfo().housesId
  }
  return userApi.counselorList.fetch(data).then((res) => {
    return res.map((item) => {
      item.key = item.userId
      item.value = item.userName
      return item
    })
  })
}

function create(opt = {}) {
  // key title
  return {
    title: opt.title,
    key: opt.key,
    placeholder: '请输入' + opt.title,
    disabled: opt.disabled || false,
    select: {
      filterable: true,
      options: opt.options || [],
      remote: (key) => {
        return getName(key)
      }
    },
    change: opt.change,
    data: opt.data
      ? opt.data
      : {
          from: (info) => {},
          to: (v, o) => {
            let info = {
              userId: null,
              name: ''
            }
            if (v) {
              info.userId = v.value
              info.name = v.label
              info[opt.key] = v.value
            }
            if (opt.to) {
              return opt.to(Object.assign(o, info))
            }
            return info
          }
        },
    rules: opt.rules || []
  }
}

// 归属顾问
let counselorList = []

function getCounselorName(userName) {
  let data = {
    userName
  }
  if (tool.getStorage('isbuildFlag') == 'buildpage') {
    data.buildingId = dt.buildInfo().housesId
  }

  return userApi.counselorList.fetch(data).then((res) => {
    counselorList = res.map((item) => {
      item.userId = item.userId
      item.key = item.workNo
      item.value = item.userName + '（' + item.workNo + '）'
      return item
    })
    return counselorList
  })
}

function createCounselorPeople(opt = {}) {
  // key title
  return {
    title: opt.title || '人员',
    key: opt.key || 'workNo',
    placeholder: opt.placeholder || '请输入人员姓名或工号',
    select: {
      clearable: true,
      filterable: true,
      options: counselorList.length > 0 ? counselorList : [],
      remote: (key) => {
        return getCounselorName(key)
      }
    },
    disabled: opt.disabled,
    data: opt.data
      ? opt.data
      : {
          from: (info) => {},
          to: (v, o) => {
            let info = {
              workNo: null,
              name: ''
            }
            if (v) {
              info.workNo = v.value
              info.name = v.label.split('（')[0]
            }
            if (opt.to) {
              return opt.to(Object.assign(o, info))
            }
            return info
          }
        }
  }
}

// 签约人
function getContractorName(keyword) {
  let data = {
    keyword
  }
  if (tool.getStorage('isbuildFlag') == 'buildpage') {
    data.buildingId = dt.buildInfo().housesId
  }
  return userApi.contractorList.fetch(data).then((res) => {
    return res.map((item) => {
      item.key = item.userId
      item.value = `${item.userName}(${item.workNo})`
      return item
    })
  })
}

function createContractor(opt = {}) {
  // key title
  return {
    title: opt.title,
    key: opt.key,
    placeholder: '请输入' + opt.title,
    select: {
      filterable: true,
      options: opt.options || [],
      remote: (key) => {
        return getContractorName(key)
      }
    },
    data: opt.data,
    change: opt.change
  }
}

// 案场外签约人查所有
function createNoBuildContractor(opt = {}) {
  // key title
  return {
    title: opt.title,
    key: opt.key,
    placeholder: '请输入' + opt.title,
    select: {
      filterable: true,
      options: opt.options || [],
      remote: (key) => {
        return getPushName(key)
      }
    },
    data: {
      from: opt.from,
      to: (v, o) => {
        let info = {
          workNo: null,
          name: ''
        }
        if (v) {
          info.workNo = v.value
          info.name = v.label.split('（')[0]
          info.userId = v.userId ? v.userId : ''
        }
        if (opt.to) {
          return o ? opt.to(Object.assign(info, o)) : opt.to(info)
        }
        return info
      }
    },
    change: opt.change
  }
}

// oa用户
function getOAName(workNo) {
  let data = {
    orgId: 2,
    page: 1,
    rows: 10,
    flag: true,
    workNo: workNo,
    userId: dt.userInfo().userId,
    roleId: dt.userInfo().role.roleId
  }
  return userApi.oaUserList.fetch(data).then((res) => {
    return res.list.map((item) => {
      item.key = item.workNo
      item.value = `${item.name}(${item.workNo})`
      return item
    })
  })
}

function createOAUser(opt = {}) {
  // key title
  return {
    title: opt.title,
    key: opt.key,
    placeholder: '请输入OA号',
    select: {
      filterable: true,
      options: opt.options || [],
      remote: (key) => {
        return getOAName(key)
      }
    },
    data: {
      from: (info) => {
        return info.workNo
      },
      to: (v, o) => {
        let info = {
          workNo: null,
          name: ''
        }
        if (v) {
          info.workNo = v.value
          info.name = v.label.split('（')[0]
        }
        if (opt.to) {
          return opt.to(Object.assign(o, info))
        }
        return info
      }
    },
    change: opt.change,
    rules: opt.rules || []
  }
}

// 搜索获取人员

let workList = []

function getOaPeople(workNo, validate) {
  if (!validate) {
    validate = 1
  }
  if (!workNo.replace(/\s+/g, '').length) {
    return new Promise((resovle, reject) => {
      resovle()
    }).then((res) => {
      workList = []
      return workList
    })
  } else {
    // if (workNo.length < 5 || workNo.length > 8) return Promise.resolve();
    return userApi.teams.getByWorkNoOrName
      .fetch({
        searchKey: workNo,
        validate
      })
      .then((res) => {
        workList = res.map((item) => {
          item.userId = item.userId
          item.key = item.workNo
          item.value = item.userName + '（' + item.workNo + '）'
          return item
        })
        return workList
      })
  }
  // validate 1有效  2无效  3全部
}

function createOaPeople(opt = {}) {
  return {
    title: opt.title || '人员',
    key: opt.key || 'workNo',
    placeholder: '请输入工号',
    select: {
      filterable: true,
      options: workList.length > 0 ? workList : [],
      remote: (key) => {
        return getOaPeople(key, opt.validate)
      }
    },
    data: opt.data,
    change: opt.change,
    rules: opt.rules || []
  }
}

function createPeople(opt = {}) {
  return {
    title: opt.title || '人员',
    key: opt.key || 'workNo',
    placeholder: opt.placeholder || '请输入员工号或姓名',
    select: {
      clearable: true,
      filterable: true,
      options: workList.length > 0 ? workList : [],
      remote: (key) => {
        return getOaPeople(key, opt.validate)
      }
    },
    data: {
      from: (info) => {
        return opt.from ? opt.from(info) : info[opt.key || 'workNo']
      },
      to: (v, o) => {
        let info = {
          workNo: null,
          name: ''
        }
        if (v) {
          info.workNo = v.value
          info.name = v.label.split('（')[0]
        }
        if (opt.to) {
          return opt.to(Object.assign(o, info))
        }
        return info
      }
    },
    rules: opt.rules || [ruleOpt.required('请输入姓名或工号')]
  }
}

// 推送顾问
let pushUserList = []

function getPushName(userNameOrWorkNo, onCase) {
  let data = {
    userNameOrWorkNo
  }
  if (tool.getStorage('isbuildFlag') == 'buildpage') {
    data.buildingId = dt.buildInfo().housesId
  } else {
    let officeIdObj = JSON.parse(dt.session.get('officeIdObj'))
    data.officeIds = officeIdObj ? officeIdObj.officeIds : []
  }

  return userApi.selectTeamUser.fetch(data).then((res) => {
    pushUserList = res.list.map((item) => {
      item.key = item.workNo
      item.value = `${item.userName}(${item.workNo}) ${onCase ? '' : item.status == '1' ? '-在案' : '-离案'}`
      return item
    })
    return pushUserList
  })
}

function createPushPeople(opt = {}, onCase) {
  return {
    title: opt.title || '顾问',
    key: opt.key || 'workNo',
    placeholder: opt.placeholder || '请输入顾问姓名或工号',
    select: {
      clearable: true,
      filterable: true,
      options: pushUserList.length > 0 ? pushUserList : [],
      remote: (key) => {
        return getPushName(key, onCase)
      }
    },
    data: {
      from: (info) => {},
      to: (v, o) => {
        let info = {
          workNo: null,
          name: ''
        }
        if (v) {
          info.workNo = v.value
          info.name = v.label.split('（')[0]
        }
        if (opt.to) {
          return opt.to(Object.assign(o, info))
        }
        return info
      }
    }
  }
}

// 姓名 手机号查询线索客户 isClue 是否线索客户 1线索客户 0非线索客户  只能在案场里用
function getNameOrPhone(nameOrPhone, isClue) {
  let data = {
    nameOrPhone,
    ...isClue
  }
  if (tool.getStorage('isbuildFlag') == 'buildpage') {
    data.buildingId = dt.buildInfo().housesId
  }
  return customerApi.clue.getCustomerByNameOrPhone.fetch(data).then((res) => {
    return res.map((item) => {
      item.key = item.userCustomerId
      item.value = item.customerName + '(' + item.customerPhone + ')'
      return item
    })
  })
}

function createNameOrPhone(opt = {}, params) {
  // key title
  return {
    title: opt.title,
    key: opt.key,
    placeholder: '请输入' + opt.title,
    select: {
      filterable: true,
      options: opt.options || [],
      remote: (key) => {
        return getNameOrPhone(key, params)
      }
    },
    data: {
      from: (info) => {},
      to: (v, o) => {
        let info = {
          workNo: null,
          name: ''
        }
        if (v) {
          info.userCustomerId = v.value
          info.name = v.label.split('(')[0]
        }
        if (opt.to) {
          return opt.to(Object.assign(o, info))
        }
        return info
      }
    }
  }
}

export default {
  create,
  createContractor,
  createNoBuildContractor,
  createOAUser,
  createOaPeople,
  createPeople,
  createCounselorPeople,
  createPushPeople,
  createNameOrPhone
}
